import axios, { AxiosInstance } from 'axios'
import { BaseResponse } from './types/base.ts'
import { RouteData } from './types/routes.ts'
import { UserInfo } from './types/user-info.ts'
import { SearchUserParams, SystemUserData, SystemUserParams, } from './types/system-user.ts'
import { SystemRoleData } from './types/system-role.ts'
import { PostAndRole } from './types/post-and-role.ts'
import { CameraData, SearchCameraListParams } from './types/camera.ts'
import { ElderRiskVague } from './types/elder-risk-vague.tsx'
import { Alarm, RiskProcessingLogsParams } from './types/alarm.tsx'
import { ElderByRiskListData, RiskType, SearchElderByRiskBody, SearchRiskTypeParams, } from './types/elder-risk.ts'
import { ElderRiskManagementData } from './types/elder-risk-management.tsx'
import { ManagementAndPhoneData } from './types/building-management-and-phone.tsx'
import { BuildingData, SearchBuildingParams } from './types/building.tsx'
import { ManagementInfo } from './types/management-info.tsx'
import { RoomInfoData } from './types/room-info.tsx'
import { RoomAndUserInfoData } from './types/room-and-user-info.tsx'
import { BuildingRoomCameraInfo } from './types/room-camera.tsx'
import { FloorsInfo } from './types/floors-info.tsx'
import { BindElderAndRoomParams } from './types/rooms-info.tsx'
import { CameraInfo } from './types/camera-info.tsx'
import { roomCameraData } from './types/camera-room-id.tsx'
import { SystemUserInfo, SystemUserInfoData } from './types/system-user-info.ts'
import { BuildingInfoData } from './types/building-info.ts'
import { UnbindCameraData } from './types/unbind-camera.ts'
import { LoginParams } from '../hooks/useLogin.ts'
import { RadarInfo } from "./types/radar-info.tsx";

export class APIError extends Error {
  readonly code: number = 0
  constructor(message: string, code: number) {
    super(message)
    this.code = code
  }
}

export class API {
  axios: AxiosInstance
  navigate: Function
  mqApi: AxiosInstance
  gifApi: AxiosInstance;
  mqApiFormata: AxiosInstance;

  constructor(navigate: Function, options?: { jwt?: string }) {
    this.axios = axios.create({
      headers: {
        Authorization: options?.jwt ? `Bearer ${options.jwt}` : undefined,
      },
      baseURL: '/api',
    })
    this.mqApi = axios.create({
      headers: {
        Authorization: options?.jwt ? `Bearer ${options.jwt}` : undefined,
      },
      baseURL: '/mq',
    })
    this.mqApiFormata = axios.create({
      headers: {
        Authorization: options?.jwt ? `Bearer ${options.jwt}` : undefined,
      },
      baseURL: '/mq',
    })
    this.gifApi = axios.create({
      headers: {
        Authorization: options?.jwt ? `Bearer ${options.jwt}` : undefined,
      },
      baseURL: '/gif',
    })
    this.navigate = navigate;

    this.axios.interceptors.response.use(
      (response) => {
        const { code, msg } = response.data
        if (msg.includes("认证失败") || code === 401) {
          // Message.warning('登录过期，请重新登录。')
          this.navigate('/auth/login');
        }
        if (code != 200) {
          if (code == 3001)
            return response
          throw new APIError(msg, code)
        }
        return response
      },
      (error) => {
        console.error('Response Error Interceptor:', error)
        return Promise.reject(error)
      },
    )
  }

  login(loginPrams: LoginParams) {
    const clientType = 'web'
    return this.axios.post<BaseResponse<string>>(
      '/login',
      {
        ...loginPrams,
        clientType,
      },
      {
        headers: {
          isToken: false,
          repeatSubmit: false,
        },
      },
    )
  }

  getRouters() {
    return this.axios.get<BaseResponse<RouteData[]>>('/getRouters')
  }

  getInfo() {
    return this.axios.get<BaseResponse<UserInfo>>('/getInfo')
  }

  getSystemUserList(params?: SearchUserParams) {
    return this.axios.get<BaseResponse<SystemUserData>>(`/system/user/list`, {
      params,
    })
  }
  getSystemUserList_(params?: SearchUserParams) {
    return this.axios.get<BaseResponse<SystemUserData>>(
      `/system/user/listFuzzy`,
      {
        params,
      },
    )
  }

  getSystemUserInfoById(userId: number | string) {
    return this.axios.get<SystemUserInfo>(`/system/user/${userId}`)
  }

  getSystemUser() {
    return this.axios.get<PostAndRole>(`/system/user`)
  }

  createSystemUser(data: SystemUserParams) {
    return this.axios.post<BaseResponse<null>>(`/system/user`, data)
  }

  deleteSystemUser(id: number) {
    return this.axios.delete(`/system/user/${id}`)
  }

  updateSystemUser(data: any) {
    return this.axios.put<BaseResponse<SystemUserData>>(`/system/user`, data)
  }

  getSystemUserById(id: string | number) {
    return this.axios.get<BaseResponse<SystemUserInfoData>>(
      `/system/user/${id}`,
    )
  }

  getSystemRoleList(params: { roleName: string }) {
    return this.axios.get<BaseResponse<SystemRoleData>>(`/system/role/list`, {
      params,
    })
  }

  getRiskStatistic() {
    return this.mqApi.get<BaseResponse<ElderByRiskListData>>(
      `/action/risk/statistics?riskType=4`,
    )
  }

  searchElderByRisk(body?: SearchElderByRiskBody) {
    return this.mqApi.post(`/action/risk/statistics`, body)
  }

  getElderByRisk(params?: SearchRiskTypeParams) {
    return this.mqApi.get(`/action/risk/statistics?riskType=${params?.riskType}&search=${params?.search}`)
  }

  getRiskAllList(params: {
    search: string;
    riskLevel: RiskType.HighAndMiddle;
    endDate: string;
    length: number;
    start: number;
    actionId: string;
    userId: string;
    startDate: string
  }) {
    return this.mqApi.get(`/action/risk/all?userId=${params.userId}&actionId=${params.actionId}&start=${params.start}&length=${params.length}&startDate=${params.startDate}&endDate=${params.endDate}&search=${params.search}&riskType=${params.riskLevel}`)
  }

  // 查询当前楼管的楼层风险信息
  getFloorRisk() {
    return this.axios.get(`/biz/action/risk/floor`)
  }

  getElderActionByUser(userId: any) {
    return this.mqApi.get(`/action/risk/report/${userId}?start=0&length=1&startDate=&endDate=&riskType=4`)
  }

  getElderReport(userId: number | string | undefined, startDate: string, endDate: string, mode: string) {
    return this.mqApi.get(`/action/analytics/${userId}/?startDate=${startDate}&endDate=${endDate}&mode=${mode}`)
  }

  getElderRisk(elderRiskVague: ElderRiskVague) {
    return this.axios.post<BaseResponse<ElderRiskManagementData>>(
      `/biz/action/risk/user`,
      elderRiskVague,
    )
  }
  //护理报告
  getNursingReport(params: any) {
    return this.mqApi.get(`action/getNursingReport/${params.roomId}?startTime=${params.startTime}`)
  }
  // 报警处理
  handleAlarm(alarm: Alarm) {
    return this.axios.post(`/biz/action/risk/deal`, alarm)
  }
  // 风险处理日志
  getRiskProcessingLogs(params: RiskProcessingLogsParams) {
    return this.mqApi.get(`/action/risk/report/${params.userId}?start=${params.start}&length=${params.length}&startDate=${params.startDate}&endDate=${params.endDate}&search=${params.search}&riskType=${params.riskLevel}`)
  }

  getManagementByBuildingId(buildingId: number | string) {
    return this.axios.get<BaseResponse<ManagementAndPhoneData>>(
      `/biz/building/phone/${buildingId}`,
    )
  }
  getBuildingList(params?: SearchBuildingParams) {
    return this.axios.get<BaseResponse<BuildingData>>(
      `/biz/building/statistic`,
      {
        params,
      },
    )
  }
  searchBuildingList(params?: SearchBuildingParams) {
    return this.axios.get<BaseResponse<BuildingData>>(
      `/biz/building/listRoomFuzzy`,
      {
        params,
      },
    )
  }
  getManagementByRoomId(roomId: number) {
    return this.axios.get<BaseResponse<ManagementInfo>>(
      `/biz/building/user/manager/${roomId}`,
    )
  }
  getRoomInfoByUser() {
    return this.axios.get<BaseResponse<RoomInfoData>>(`/biz/building/user/room`)
  }
  getRoomAndUserByRoomId(roomId: number) {
    return this.axios.get<BaseResponse<RoomAndUserInfoData>>(
      `/biz/building/user/room/${roomId}`,
    )
  }

  saveBuilding(data: BuildingRoomCameraInfo) {
    return this.axios.post<BaseResponse<number>>(`/biz/building/save/all`, data)
  }

  updateBuilding(data: BuildingRoomCameraInfo) {
    return this.axios.post<BaseResponse<boolean>>(
      `/biz/building/update/building`,
      data,
    )
  }

  updateFloors(data: FloorsInfo) {
    return this.axios.post<BaseResponse<boolean>>(
      `/biz/building/update/floor`,
      data,
    )
  }

  updateRooms(data: BindElderAndRoomParams) {
    return this.axios.post<BaseResponse<boolean>>(
      `/biz/building/update/room`,
      data,
    )
  }

  bindActionTable(data: BindElderAndRoomParams) {
    return this.mqApi.put<BaseResponse<boolean>>(
      `/action/bind/${data.userId}`
    )
  }

  addCamera(data: CameraInfo) {
    return this.axios.post<BaseResponse<boolean>>(`/biz/camera/add`, data)
  }

  updateCamera(data: CameraInfo) {
    return this.axios.post<BaseResponse<boolean>>(`/biz/camera/update`, data)
  }

  deleteCamera(id: number) {
    return this.axios.get<BaseResponse<boolean>>(`/biz/camera/remove`, {
      params: { id },
    })
  }

  getUnbindCameraList(params?: SearchCameraListParams) {
    return this.axios.get<BaseResponse<UnbindCameraData>>(
      `/biz/camera/list/unbind`,
      {
        params,
      },
    )
  }

  getCameraByRoomId(roomId: number) {
    return this.axios.get<BaseResponse<roomCameraData>>(
      `/biz/camera/room/${roomId}`,
    )
  }

  getCameraById(cameraId: number | string) {
    return this.axios.get<BaseResponse<CameraInfo>>(`/biz/camera/${cameraId}`)
  }

  getUserReport() {
    return this.axios.get(`/biz/report/list`)
  }

  getVideoList() {
    return this.axios.get(`/biz/video/list`)
  }

  getBuildingAdminList() {
    return this.axios.get(`/biz/buildingAdmin/list`)
  }

  getUserList() {
    return this.axios.get(`/biz/user/list`)
  }

  getRiskList() {
    return this.axios.get(`/biz/risk/list`)
  }

  getBuildingInfoById(buildingId: number | string) {
    return this.axios.get<BaseResponse<BuildingInfoData>>(
      `/biz/building/all/${buildingId}`,
    )
  }

  updateReport(param: {
    data: { method: number; report: { nickName: string | null; userId: string | null }; time: string; };
    videoList: string;
    id: number | string;
    userId: number | string
  }) {
    const formData = new FormData();
    let dataObj = { text: '', ...param.data }

    formData.append('pics', '');
    formData.append('files', '');
    formData.append("data", JSON.stringify(dataObj))


    return this.mqApi.post(`/action/risk/report/0/${param.userId}?suid=${param.videoList}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  }

  deleteRiskProcessingLog1(param: { id: number; suid: string; userId: number | string }) {
    return this.mqApi.delete(`/action/risk/report/0/${param.userId}?suid=${param.suid}`)
  }


  deleteRiskProcessingLog(param: {
    data: { pics: ""; files: ""; method: number; report: { nickName: any; userId: string | null }; time: string };
    id: number;
    suid: string;
    userId: number | string
  }) {
    const formData = new FormData();

    // Append `param.data` fields to the `FormData` object
    Object.keys(param.data).forEach((key) => {
      if (param.data.hasOwnProperty(key)) {
        // 确保值为字符串类型
        const value = param.data[key as keyof typeof param.data];
        if (value !== null && value !== undefined) {
          if (value instanceof Object) {
            formData.append("report", JSON.stringify(param.data.report))
          } else {
            formData.append(key, String(value));

          }
        } else {

          formData.append(key, '')

        }
      }
    });

    return this.mqApi.delete(`/action/risk/report/0/${param.userId}?suid=${param.suid}`, {
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      }
    }

    );
    // return axios.delete(`/mq/action/risk/report/0/${param.userId}?suid=${param.suid}`, {
    //   data: formData, // 关键：DELETE 请求的请求体需要用 `data` 字段
    //   headers: {
    //     'Content-Type': 'multipart/form-data', // 需要显式设置
    //   },
    // })
  }



  getRadarList(params?: SearchCameraListParams) {
    return this.axios.get<BaseResponse<CameraData>>(`/biz/radar/list`, {
      params,
    })
  }

  getCameraList(params?: SearchCameraListParams) {
    return this.axios.get<BaseResponse<CameraData>>(`/biz/camera/list`, {
      params,
    })
  }

  getRadarById(radarId: number | string) {
    return this.axios.get<BaseResponse<CameraInfo>>(`/biz/radar/${radarId}`)
  }

  getGif(suid: number | string) {
    return this.mqApi.get(`/files/src/playback/${suid}.gif?${new Date().getTime()}`)
  }

  addRadar(data: RadarInfo) {
    return this.axios.post<BaseResponse<boolean>>(`/biz/radar/add`, data)
  }

  updateRadar(data: RadarInfo) {
    return this.axios.post<BaseResponse<boolean>>(`/biz/radar/update`, data)
  }

  deleteRadar(id: number) {
    return this.axios.delete<BaseResponse<boolean>>(`/biz/radar/remove`, {
      params: { id },
    })
  }
}
